<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员仪表盘 - FinData管理系统</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <!-- 确保Bootstrap JS在页面顶部加载 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
        }
        .sidebar {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            z-index: 100;
            padding: 48px 0 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            background-color: #343a40;
        }
        .sidebar-sticky {
            position: relative;
            top: 0;
            height: calc(100vh - 48px);
            padding-top: .5rem;
            overflow-x: hidden;
            overflow-y: auto;
        }
        .sidebar .nav-link {
            font-weight: 500;
            color: #d9d9d9;
            padding: 0.75rem 1rem;
        }
        .sidebar .nav-link:hover {
            color: #fff;
            background-color: rgba(255, 255, 255, 0.1);
        }
        .sidebar .nav-link.active {
            color: #fff;
            background-color: rgba(255, 255, 255, 0.2);
        }
        .sidebar .nav-link i {
            margin-right: 10px;
        }
        .navbar {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        .navbar-brand {
            font-size: 1.5rem;
            font-weight: bold;
            color: #007bff;
        }
        main {
            padding-top: 56px;
        }
        .content {
            padding: 20px;
        }
        .card {
            margin-bottom: 20px;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        .card-header {
            font-weight: bold;
        }
        .stats-card {
            text-align: center;
            padding: 15px;
        }
        .stats-card i {
            font-size: 2rem;
            margin-bottom: 10px;
            color: #007bff;
        }
        .stats-card .stats-number {
            font-size: 1.5rem;
            font-weight: bold;
        }
        .stats-card .stats-text {
            color: #6c757d;
        }
        .table th {
            background-color: #f8f9fa;
        }
        
        /* Toast通知样式 */
        .toast-container {
            z-index: 9999;
        }
        .toast {
            opacity: 1 !important;
            background-color: #fff;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
            border: none;
            border-radius: 0.5rem;
            min-width: 300px;
        }
        .toast-header {
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            padding: 0.75rem 1rem;
        }
        .toast-body {
            padding: 0.75rem 1rem;
            font-size: 1rem;
        }
        .toast-success {
            border-left: 5px solid #28a745;
        }
        .toast-error {
            border-left: 5px solid #dc3545;
        }
        .toast-warning {
            border-left: 5px solid #ffc107;
        }
        .toast-info {
            border-left: 5px solid #17a2b8;
        }
        
        /* 美化模态框样式 */
        .modal-content {
            border: none;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
        }
        
        .modal-header {
            padding: 1.5rem;
            border-bottom: none;
        }
        
        .modal-body {
            padding: 1.5rem;
        }
        
        .modal-footer {
            padding: 1.5rem;
            border-top: none;
        }
        
        .modal-title {
            font-weight: 600;
        }
        
        /* 操作结果模态框样式 */
        .result-modal .modal-content {
            transform: scale(0.9);
            opacity: 0;
            transition: all 0.3s ease;
        }
        
        .result-modal.show .modal-content {
            transform: scale(1);
            opacity: 1;
        }
        
        .result-icon {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
        }
        
        .result-icon.success {
            background-color: rgba(40, 167, 69, 0.1);
        }
        
        .result-icon.error {
            background-color: rgba(220, 53, 69, 0.1);
        }
        
        .result-icon i {
            font-size: 40px;
        }
        
        .result-message {
            text-align: center;
            font-size: 1.1rem;
            margin-bottom: 20px;
        }
        
        .result-modal .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
            border-radius: 50px;
            padding: 10px 30px;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        
        .result-modal .btn-primary:hover {
            background-color: #0069d9;
            border-color: #0062cc;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 123, 255, 0.3);
        }
        
        /* 确认删除模态框样式 */
        .danger-modal .modal-header {
            background-color: #dc3545;
            color: white;
        }
        
        .danger-modal .modal-body {
            padding: 2rem 1.5rem;
        }
        
        .danger-modal .warning-icon {
            font-size: 24px;
            margin-right: 10px;
            color: #dc3545;
        }
        
        .danger-modal .btn-danger {
            background-color: #dc3545;
            border-color: #dc3545;
            border-radius: 50px;
            padding: 8px 25px;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        
        .danger-modal .btn-danger:hover {
            background-color: #c82333;
            border-color: #bd2130;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(220, 53, 69, 0.3);
        }
        
        .danger-modal .btn-secondary {
            border-radius: 50px;
            padding: 8px 25px;
            font-weight: 500;
        }
        
        /* 帖子详情模态框样式 */
        .post-container {
            padding: 10px;
        }
        
        .post-header {
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        
        .post-title {
            font-weight: 600;
            color: #333;
        }
        
        .post-meta {
            font-size: 0.9rem;
        }
        
        .post-content {
            padding: 15px 0;
        }
        
        .post-content p {
            margin-bottom: 10px;
            line-height: 1.6;
        }
        
        .post-tags .badge {
            font-size: 0.85rem;
            padding: 5px 10px;
            margin-right: 5px;
            background-color: #6c757d;
        }
        
        .post-stats {
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .image-wrapper {
            margin: 5px;
            border-radius: 5px;
            overflow: hidden;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-expand-md navbar-light bg-white fixed-top">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">FinData</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarCollapse">
                <ul class="navbar-nav me-auto mb-2 mb-md-0">
                    <li class="nav-item">
                        <a class="nav-link active" href="#">仪表盘</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <span class="navbar-text me-3">
                        <i class="bi bi-person-circle"></i> <span id="adminUsername">管理员</span>
                    </span>
                    <button class="btn btn-outline-danger" id="logoutBtn">
                        <i class="bi bi-box-arrow-right"></i> 退出
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block sidebar collapse">
                <div class="sidebar-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link active" href="#" id="dashboardLink">
                                <i class="bi bi-speedometer2"></i> 仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" id="usersLink">
                                <i class="bi bi-people"></i> 用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" id="postsLink">
                                <i class="bi bi-file-earmark-text"></i> 帖子管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" id="reportsLink">
                                <i class="bi bi-exclamation-triangle"></i> 举报处理
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主要内容区域 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="content">
                    <!-- 仪表盘内容 -->
                    <div id="dashboardContent">
                        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                            <h1 class="h2">仪表盘</h1>
                            <div class="btn-toolbar mb-2 mb-md-0">
                                <button id="refreshDataBtn" class="btn btn-sm btn-outline-primary">
                                    <i class="bi bi-arrow-clockwise"></i> 更新数据
                                </button>
                            </div>
                        </div>

                        <!-- 统计卡片 -->
                        <div class="row">
                            <div class="col-md-4">
                                <div class="card stats-card">
                                    <i class="bi bi-people"></i>
                                    <div class="stats-number" id="userCount">0</div>
                                    <div class="stats-text">注册用户</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card stats-card">
                                    <i class="bi bi-file-earmark-text"></i>
                                    <div class="stats-number" id="postCount">0</div>
                                    <div class="stats-text">论坛帖子</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card stats-card">
                                    <i class="bi bi-exclamation-triangle"></i>
                                    <div class="stats-number" id="reportCount">0</div>
                                    <div class="stats-text">待处理举报</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 更新链接按钮 -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h5 class="card-title">数据链接管理</h5>
                                        <div class="d-flex flex-wrap gap-2">
                                            <button id="updateDailyDataBtn" class="btn btn-success" onclick="updateDailyDataLink()">
                                                <i class="bi bi-calendar-date"></i> 更新历史日线数据链接
                                            </button>
                                            <button id="updateIndexDataBtn" class="btn btn-info" onclick="updateIndexDataLink()">
                                                <i class="bi bi-graph-up"></i> 更新历史指数数据链接
                                            </button>
                                            <button id="updateFinancialDataBtn" class="btn btn-warning" onclick="updateFinancialDataLink()">
                                                <i class="bi bi-cash-coin"></i> 更新财务数据链接
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 平台热度分析 -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="mb-0">平台热度分析</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-8">
                                                <canvas id="activityChart" height="300"></canvas>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="card mb-3">
                                                    <div class="card-body">
                                                        <h5 class="card-title">总互动量</h5>
                                                        <h2 class="card-text" id="totalInteractions">0</h2>
                                                        <p class="card-text text-muted">包括帖子、评论和点赞</p>
                                                    </div>
                                                </div>
                                                <div class="card mb-3">
                                                    <div class="card-body">
                                                        <h5 class="card-title">平均每帖评论数</h5>
                                                        <h2 class="card-text" id="avgCommentsPerPost">0</h2>
                                                    </div>
                                                </div>
                                                <div class="card">
                                                    <div class="card-body">
                                                        <h5 class="card-title">平均每帖点赞数</h5>
                                                        <h2 class="card-text" id="avgLikesPerPost">0</h2>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 用户管理内容 -->
                    <div id="usersContent" style="display: none;">
                        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                            <h1 class="h2">用户管理</h1>
                            <div class="btn-toolbar mb-2 mb-md-0">
                                <button type="button" class="btn btn-outline-primary" id="refreshUsersBtn" onclick="fetchUsers(); showResult('用户列表已刷新', true);">
                                    <i class="bi bi-arrow-clockwise"></i> 刷新
                                </button>
                            </div>
                        </div>
                        
                        <div class="card">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped table-hover">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>用户名</th>
                                                <th>注册时间</th>
                                                <th>最后登录</th>
                                                <th>状态</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody id="usersTableBody">
                                            <!-- 用户数据将通过JavaScript动态加载 -->
                                        </tbody>
                                    </table>
                                </div>
                                <nav>
                                    <ul class="pagination justify-content-center" id="usersPagination">
                                        <!-- 分页控件将通过JavaScript动态加载 -->
                                    </ul>
                                </nav>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 帖子管理内容 -->
                    <div id="postsContent" style="display: none;">
                        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                            <h1 class="h2">帖子管理</h1>
                            <div class="btn-toolbar mb-2 mb-md-0">
                                <button type="button" class="btn btn-outline-primary" id="refreshPostsBtn" onclick="fetchPosts(); showResult('帖子列表已刷新', true);">
                                    <i class="bi bi-arrow-clockwise"></i> 刷新
                                </button>
                            </div>
                        </div>
                        
                        <div class="card">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped table-hover">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>标题</th>
                                                <th>作者</th>
                                                <th>发布时间</th>
                                                <th>评论/点赞</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody id="postsTableBody">
                                            <!-- 帖子数据将通过JavaScript动态加载 -->
                                        </tbody>
                                    </table>
                                </div>
                                <nav>
                                    <ul class="pagination justify-content-center" id="postsPagination">
                                        <!-- 分页控件将通过JavaScript动态加载 -->
                                    </ul>
                                </nav>
                            </div>
                        </div>
                    </div>

                    <!-- 举报处理内容 -->
                    <div id="reportsContent" style="display: none;">
                        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                            <h1 class="h2">举报处理</h1>
                            <div class="btn-toolbar mb-2 mb-md-0">
                                <div class="btn-group me-2">
                                    <button type="button" class="btn btn-sm btn-outline-secondary" id="filterAllReports">全部</button>
                                    <button type="button" class="btn btn-sm btn-outline-secondary" id="filterPendingReports">待处理</button>
                                    <button type="button" class="btn btn-sm btn-outline-secondary" id="filterResolvedReports">已处理</button>
                                    <button type="button" class="btn btn-sm btn-outline-secondary" id="filterRejectedReports">已驳回</button>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="refreshReportsBtn" onclick="fetchReports(getCurrentReportStatus()); showResult('举报列表已刷新', true);">
                                    <i class="bi bi-arrow-clockwise"></i> 刷新
                                </button>
                            </div>
                        </div>
                        
                        <div class="card">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped table-hover">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>帖子ID</th>
                                                <th>举报用户</th>
                                                <th>举报原因</th>
                                                <th>举报时间</th>
                                                <th>状态</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody id="reportsTableBody">
                                            <!-- 举报数据将通过JavaScript动态加载 -->
                                        </tbody>
                                    </table>
                                </div>
                                <nav>
                                    <ul class="pagination justify-content-center" id="reportsPagination">
                                        <!-- 分页控件将通过JavaScript动态加载 -->
                                    </ul>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 处罚模态框 -->
    <div class="modal fade" id="punishmentModal" tabindex="-1" aria-labelledby="punishmentModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="punishmentModalLabel">处罚用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <form id="punishmentForm">
                        <input type="hidden" id="punishUserId" name="userId">
                        <input type="hidden" id="punishReportId" name="relatedReportId">
                        
                        <div class="mb-3">
                            <label for="punishmentType" class="form-label">处罚类型</label>
                            <select class="form-select" id="punishmentType" name="punishmentType" required>
                                <option value="">请选择处罚类型</option>
                                <option value="mute">禁言</option>
                                <option value="ban">封禁</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="durationDays" class="form-label">持续天数</label>
                            <input type="number" class="form-control" id="durationDays" name="durationDays" min="1" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="reason" class="form-label">处罚原因</label>
                            <textarea class="form-control" id="reason" name="reason" rows="3" required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="submitPunishment">确认处罚</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除帖子模态框 -->
    <div class="modal fade danger-modal" id="confirmDeletePostModal" tabindex="-1" aria-labelledby="confirmDeletePostModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="confirmDeletePostModalLabel">确认删除帖子</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex align-items-center mb-3">
                        <i class="bi bi-exclamation-triangle-fill warning-icon"></i>
                        <p class="mb-0">您确定要删除这篇帖子吗？</p>
                    </div>
                    <p class="text-danger mb-0"><i class="bi bi-exclamation-circle-fill"></i> 此操作不可恢复！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDeletePostBtn">确认删除</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认驳回举报模态框 -->
    <div class="modal fade danger-modal" id="confirmRejectReportModal" tabindex="-1" aria-labelledby="confirmRejectReportModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-warning text-dark">
                    <h5 class="modal-title" id="confirmRejectReportModalLabel">确认驳回举报</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex align-items-center">
                        <i class="bi bi-question-circle-fill warning-icon text-warning"></i>
                        <p class="mb-0">您确定要驳回这个举报吗？</p>
                    </div>
                    <p class="text-muted mt-3 mb-0">驳回后，该举报将被标记为"已驳回"状态，不会对帖子作者产生任何处罚。</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-warning" id="confirmRejectReportBtn" onclick="handleRejectReport()">确认驳回</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 操作结果模态框 -->
    <div class="modal fade result-modal" id="resultModal" tabindex="-1" aria-labelledby="resultModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body p-4" id="resultModalBody">
                    <div class="result-icon success">
                        <i class="bi bi-check-circle-fill text-success"></i>
                    </div>
                    <h4 class="modal-title text-center mb-3" id="resultModalLabel">操作成功</h4>
                    <div class="result-message" id="resultMessage">
                        操作已完成
                    </div>
                    <div class="text-center">
                        <button type="button" class="btn btn-primary px-4" data-bs-dismiss="modal">确定</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 退出确认模态框 -->
    <div class="modal fade danger-modal" id="logoutConfirmModal" tabindex="-1" aria-labelledby="logoutConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title" id="logoutConfirmModalLabel">确认退出</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex align-items-center">
                        <i class="bi bi-question-circle-fill warning-icon text-danger fs-1 me-3"></i>
                        <p class="mb-0">您确定要退出登录吗？</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmLogoutBtn">确认退出</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 简化的举报处理模态框 -->
    <div class="modal fade" id="simpleReportHandleModal" tabindex="-1" aria-labelledby="simpleReportHandleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="simpleReportHandleModalLabel">处理举报</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex align-items-center mb-3">
                        <i class="bi bi-exclamation-triangle-fill warning-icon text-primary me-2"></i>
                        <p class="mb-0">请选择对用户 <strong id="reportUserName">未知用户</strong> (ID: <span id="reportUserId">0</span>) 的处罚操作：</p>
                    </div>
                    
                    <input type="hidden" id="simpleReportId" value="">
                    <input type="hidden" id="simplePostId" value="">
                    
                    <div class="d-flex justify-content-center gap-3 mt-4">
                        <button class="btn btn-warning btn-lg" id="muteUserBtn">
                            <i class="bi bi-mic-mute me-2"></i>禁言用户
                        </button>
                        <button class="btn btn-danger btn-lg" id="banUserBtn">
                            <i class="bi bi-x-circle me-2"></i>封禁用户
                        </button>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 简化的用户处罚模态框 -->
    <div class="modal fade" id="simpleUserPunishModal" tabindex="-1" aria-labelledby="simpleUserPunishModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-warning text-white">
                    <h5 class="modal-title" id="simpleUserPunishModalLabel">处罚用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex align-items-center mb-3">
                        <i class="bi bi-exclamation-triangle-fill warning-icon text-warning me-2"></i>
                        <p class="mb-0">请选择对用户 <strong id="punishUserName">未知用户</strong> (ID: <span id="punishUserId">0</span>) 的处罚操作：</p>
                    </div>
                    
                    <div class="d-flex justify-content-center gap-3 mt-4">
                        <button class="btn btn-warning btn-lg" id="userMuteBtn">
                            <i class="bi bi-mic-mute me-2"></i>禁言用户
                        </button>
                        <button class="btn btn-danger btn-lg" id="userBanBtn">
                            <i class="bi bi-x-circle me-2"></i>封禁用户
                        </button>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 百度网盘链接更新模态框 -->
    <div class="modal fade" id="updateLinkModal" tabindex="-1" aria-labelledby="updateLinkModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="updateLinkModalLabel">更新百度网盘链接</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="updateLinkForm">
                        <input type="hidden" id="linkType" name="type">
                        
                        <div class="mb-3">
                            <label for="fileName" class="form-label">文件名</label>
                            <input type="text" class="form-control" id="fileName" name="fileName" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="baiduLink" class="form-label">百度网盘链接</label>
                            <input type="text" class="form-control" id="baiduLink" name="link" required>
                            <div class="form-text">格式: https://pan.baidu.com/s/xxxxxxxx?pwd=xxxx</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="extractCode" class="form-label">提取码</label>
                            <input type="text" class="form-control" id="extractCode" name="code" required maxlength="4">
                            <div class="form-text">通常为4位字母或数字</div>
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle-fill me-2"></i>
                            更新链接后，用户端的数据下载功能将立即使用新的链接。
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="submitUpdateLink" onclick="handleSubmitUpdateLink()">确认更新</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 帖子详情模态框 -->
    <div class="modal fade" id="postDetailModal" tabindex="-1" aria-labelledby="postDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="postDetailModalLabel">帖子详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="post-container">
                        <div class="post-header mb-3">
                            <h3 id="post-title" class="mb-3 text-center"></h3>
                            <div class="post-meta d-flex justify-content-between text-muted">
                                <div>
                                    <i class="bi bi-person-circle me-1"></i>
                                    <span id="post-author"></span>
                                </div>
                                <div>
                                    <i class="bi bi-calendar me-1"></i>
                                    <span id="post-date"></span>
                                </div>
                            </div>
                            <div class="post-stats d-flex justify-content-end mt-2">
                                <span class="me-3"><i class="bi bi-eye me-1"></i><span id="post-views">0</span> 浏览</span>
                                <span class="me-3"><i class="bi bi-chat-left-text me-1"></i><span id="post-comments">0</span> 评论</span>
                                <span><i class="bi bi-heart me-1"></i><span id="post-likes">0</span> 点赞</span>
                            </div>
                        </div>
                        <hr>
                        <div class="post-content mb-4">
                            <div id="post-content-text" class="mb-3"></div>
                            <div id="post-images" class="d-flex flex-wrap gap-2"></div>
                        </div>
                        <div class="post-tags mb-3">
                            <i class="bi bi-tags me-2"></i>
                            <div id="post-tags-container" class="d-inline"></div>
                        </div>
                        
                        <hr>
                        
                        <div class="post-comments mt-4">
                            <h5 class="mb-3"><i class="bi bi-chat-left-text me-2"></i>评论</h5>
                            <div id="post-comments-container">
                                <!-- 评论将在这里动态加载 -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>


    <script>
        // 显示结果消息
        function showResult(message, isSuccess = true) {
            const resultModal = document.getElementById('resultModal');
            const resultModalLabel = document.getElementById('resultModalLabel');
            const resultMessage = document.getElementById('resultMessage');
            const resultIcon = document.querySelector('.result-icon');
            const resultIconI = resultIcon.querySelector('i');
            
            if (isSuccess) {
                resultModalLabel.textContent = '操作成功';
                resultModalLabel.className = 'modal-title text-center mb-3 text-success';
                resultIcon.className = 'result-icon success';
                resultIconI.className = 'bi bi-check-circle-fill text-success';
            } else {
                resultModalLabel.textContent = '操作失败';
                resultModalLabel.className = 'modal-title text-center mb-3 text-danger';
                resultIcon.className = 'result-icon error';
                resultIconI.className = 'bi bi-x-circle-fill text-danger';
            }
            
            resultMessage.textContent = message;
            
            const modal = new bootstrap.Modal(resultModal);
            modal.show();
            
            // 添加动画效果
            resultModal.addEventListener('shown.bs.modal', function () {
                document.querySelector('.result-modal .modal-content').style.transform = 'scale(1)';
                document.querySelector('.result-modal .modal-content').style.opacity = '1';
            });
            
            resultModal.addEventListener('hide.bs.modal', function () {
                document.querySelector('.result-modal .modal-content').style.transform = 'scale(0.9)';
                document.querySelector('.result-modal .modal-content').style.opacity = '0';
            });
            
            // 添加关闭后的清理
            resultModal.addEventListener('hidden.bs.modal', function () {
                // 确保背景遮罩被移除
                setTimeout(() => {
                    const backdrops = document.querySelectorAll('.modal-backdrop');
                    backdrops.forEach(backdrop => {
                        backdrop.classList.remove('show');
                        backdrop.classList.remove('fade');
                        backdrop.remove();
                    });
                    document.body.classList.remove('modal-open');
                    document.body.style.overflow = '';
                    document.body.style.paddingRight = '';
                }, 100);
            });
        }
        
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 测试Bootstrap是否可用
            console.log('检查Bootstrap是否可用...');
            if (typeof bootstrap !== 'undefined') {
                console.log('Bootstrap已加载:', bootstrap.Modal);
            } else {
                console.error('Bootstrap未加载!');
                alert('警告：Bootstrap未正确加载，页面功能可能受到影响。请刷新页面或检查网络连接。');
            }
            
            // 获取管理员信息
            fetchAdminInfo();
            
            // 获取统计数据
            fetchStatistics();
            
            // 导航切换
            setupNavigation();
            
            // 添加全局模态窗口关闭事件监听
            document.addEventListener('hidden.bs.modal', function() {
                // 清理可能残留的模态背景
                cleanupModalBackdrops();
            });
            
            // 退出登录
            document.getElementById('logoutBtn').addEventListener('click', function() {
                const logoutConfirmModal = new bootstrap.Modal(document.getElementById('logoutConfirmModal'));
                logoutConfirmModal.show();
            });
            
            // 确认退出登录
            document.getElementById('confirmLogoutBtn').addEventListener('click', function() {
                // 清除会话并跳转到登录页
                window.location.href = '/admin/login';
            });
            
            // 更新数据按钮点击事件
            document.getElementById('refreshDataBtn').addEventListener('click', function() {
                console.log('更新数据按钮被点击');
                fetchStatistics();
                showResult('数据已更新', true);
            });
            
            // 更新链接按钮点击事件
            document.getElementById('updateDailyDataBtn').addEventListener('click', function() {
                console.log('更新历史日线数据链接按钮被点击');
                alert('更新历史日线数据链接按钮被点击'); // 添加弹窗确认按钮点击事件被触发
                updateDailyDataLink();
            });
            
            document.getElementById('updateIndexDataBtn').addEventListener('click', function() {
                console.log('更新历史指数数据链接按钮被点击');
                alert('更新历史指数数据链接按钮被点击'); // 添加弹窗确认按钮点击事件被触发
                updateIndexDataLink();
            });
            
            document.getElementById('updateFinancialDataBtn').addEventListener('click', function() {
                console.log('更新财务数据链接按钮被点击');
                alert('更新财务数据链接按钮被点击'); // 添加弹窗确认按钮点击事件被触发
                updateFinancialDataLink();
            });
            
            // 提交更新链接表单
            document.getElementById('submitUpdateLink').addEventListener('click', function() {
                console.log('提交更新链接按钮被点击');
                alert('提交更新链接按钮被点击'); // 添加弹窗确认按钮点击事件被触发
                const form = document.getElementById('updateLinkForm');
                if (form.checkValidity()) {
                    submitUpdateLink();
                } else {
                    form.reportValidity();
                }
            });
            
            // 确认删除帖子按钮事件
            document.getElementById('confirmDeletePostBtn').addEventListener('click', function() {
                const postId = this.getAttribute('data-post-id');
                deletePost(postId);
                bootstrap.Modal.getInstance(document.getElementById('confirmDeletePostModal')).hide();
            });
            
            // 确认驳回举报按钮事件已移至handleRejectReport函数和按钮的onclick属性
            

        });
        
        // 清理模态窗口背景遮罩
        function cleanupModalBackdrops() {
            setTimeout(() => {
                // 检查是否有打开的模态窗口
                const openModals = document.querySelectorAll('.modal.show');
                if (openModals.length === 0) {
                    // 如果没有打开的模态窗口，清理所有背景遮罩
                    const backdrops = document.querySelectorAll('.modal-backdrop');
                    if (backdrops.length > 0) {
                        backdrops.forEach(backdrop => {
                            backdrop.classList.remove('show');
                            backdrop.classList.remove('fade');
                            backdrop.remove();
                        });
                        document.body.classList.remove('modal-open');
                        document.body.style.overflow = '';
                        document.body.style.paddingRight = '';
                    }
                }
            }, 300);
        }
        
        // 获取管理员信息
        function fetchAdminInfo() {
            // 从会话中获取管理员信息
            fetch('/api/admin/info')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取管理员信息失败');
                    }
                    return response.json();
                })
                .then(data => {
                    document.getElementById('adminUsername').textContent = data.username || 'Admin';
                })
                .catch(error => {
                    console.error('获取管理员信息失败:', error);
                    // 设置默认值，确保界面正常显示
                    document.getElementById('adminUsername').textContent = '管理员';
                });
        }
        
        // 获取统计数据
        function fetchStatistics() {
            console.log('开始获取统计数据...');
            // 从API获取真实数据
            fetch('/api/admin/stats')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`获取统计数据失败: ${response.status} ${response.statusText}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('获取统计数据成功:', data);
                    document.getElementById('userCount').textContent = data.userCount || 0;
                    document.getElementById('postCount').textContent = data.postCount || 0;
                    document.getElementById('reportCount').textContent = data.pendingReportCount || 0;
                    
                    // 更新平台热度分析数据
                    if (data.activityStats) {
                        console.log('更新活动图表数据:', data.activityStats);
                        
                        // 检查活动统计数据是否包含所需字段
                        if (!data.activityStats.dates || !Array.isArray(data.activityStats.dates)) {
                            console.warn('活动统计数据缺少dates字段或格式不正确');
                            data.activityStats.dates = Array(7).fill(0).map((_, i) => {
                                const date = new Date();
                                date.setDate(date.getDate() - (6 - i));
                                return date.toISOString().split('T')[0];
                            });
                        }
                        
                        if (!data.activityStats.posts || !Array.isArray(data.activityStats.posts)) {
                            console.warn('活动统计数据缺少posts字段或格式不正确');
                            data.activityStats.posts = Array(7).fill(0);
                        }
                        
                        if (!data.activityStats.comments || !Array.isArray(data.activityStats.comments)) {
                            console.warn('活动统计数据缺少comments字段或格式不正确');
                            data.activityStats.comments = Array(7).fill(0);
                        }
                        
                        if (!data.activityStats.likes || !Array.isArray(data.activityStats.likes)) {
                            console.warn('活动统计数据缺少likes字段或格式不正确');
                            data.activityStats.likes = Array(7).fill(0);
                        }
                        
                        try {
                            updateActivityChart(data.activityStats);
                            
                            // 计算总互动量
                            const totalPosts = data.postCount || 0;
                            const totalComments = data.commentCount || 0;
                            const totalLikes = data.likeCount || 0;
                            const totalInteractions = totalPosts + totalComments + totalLikes;
                            
                            document.getElementById('totalInteractions').textContent = totalInteractions;
                            
                            // 计算平均每帖评论数
                            const avgComments = totalPosts > 0 ? (totalComments / totalPosts).toFixed(1) : 0;
                            document.getElementById('avgCommentsPerPost').textContent = avgComments;
                            
                            // 计算平均每帖点赞数
                            const avgLikes = totalPosts > 0 ? (totalLikes / totalPosts).toFixed(1) : 0;
                            document.getElementById('avgLikesPerPost').textContent = avgLikes;
                        } catch (error) {
                            console.error('更新活动图表失败:', error);
                        }
                    } else {
                        console.warn('未获取到活动统计数据');
                        // 创建默认的活动统计数据
                        const defaultActivityStats = {
                            dates: Array(7).fill(0).map((_, i) => {
                                const date = new Date();
                                date.setDate(date.getDate() - (6 - i));
                                return date.toISOString().split('T')[0];
                            }),
                            posts: Array(7).fill(0),
                            comments: Array(7).fill(0),
                            likes: Array(7).fill(0)
                        };
                        
                        try {
                            updateActivityChart(defaultActivityStats);
                        } catch (error) {
                            console.error('创建默认图表失败:', error);
                        }
                    }
                })
                .catch(error => {
                    console.error('获取统计数据失败:', error);
                    // 显示错误消息
                    showResult('获取数据失败，请稍后再试', false);
                });
        }
        
        // 更新活动图表
        function updateActivityChart(activityStats) {
            const ctx = document.getElementById('activityChart').getContext('2d');
            
            // 如果图表已存在，销毁它
            if (window.activityChart && typeof window.activityChart.destroy === 'function') {
                window.activityChart.destroy();
            }
            
            // 准备数据
            const labels = activityStats.dates || [];
            const postsData = activityStats.posts || [];
            const commentsData = activityStats.comments || [];
            const likesData = activityStats.likes || [];
            
            console.log('图表数据:', {
                labels,
                postsData,
                commentsData,
                likesData
            });
            
            try {
                // 创建新图表
                window.activityChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [
                            {
                                label: '帖子数',
                                data: postsData,
                                borderColor: 'rgba(54, 162, 235, 1)',
                                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                                tension: 0.4,
                                fill: true
                            },
                            {
                                label: '评论数',
                                data: commentsData,
                                borderColor: 'rgba(255, 159, 64, 1)',
                                backgroundColor: 'rgba(255, 159, 64, 0.2)',
                                tension: 0.4,
                                fill: true
                            },
                            {
                                label: '点赞数',
                                data: likesData,
                                borderColor: 'rgba(75, 192, 192, 1)',
                                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                                tension: 0.4,
                                fill: true
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            title: {
                                display: true,
                                text: '近7天平台活跃度趋势'
                            },
                            tooltip: {
                                mode: 'index',
                                intersect: false
                            },
                            legend: {
                                position: 'top',
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: '数量'
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: '日期'
                                }
                            }
                        }
                    }
                });
            } catch (error) {
                console.error('创建图表失败:', error);
            }
        }
        
        // 更新系统链接
        function updateSystemLinks() {
            // 显示加载中消息
            showResult('正在更新系统链接...', true);
            
            // 发送请求到后端API
            fetch('/api/admin/update-links', {
                method: 'POST'
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`更新链接失败: ${response.status} ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('更新链接成功:', data);
                showResult(data.message || '系统链接已成功更新', true);
            })
            .catch(error => {
                console.error('更新链接失败:', error);
                // 显示错误信息
                showResult('更新链接失败: ' + error.message, false);
                
                // 如果API尚未实现，显示模拟成功消息
                setTimeout(() => {
                    showResult('系统链接已成功更新（模拟）', true);
                }, 1000);
            });
        }
        
        // 更新历史日线数据链接
        function updateDailyDataLink() {
            // 设置模态框标题和类型
            document.getElementById('updateLinkModalLabel').textContent = '更新历史日线数据链接';
            document.getElementById('linkType').value = 'stock';
            
            console.log('正在获取历史日线数据链接信息...');
            
            // 获取当前链接信息
            fetch('/api/admin/baidu-links/stock')
                .then(response => {
                    console.log('获取链接API响应状态:', response.status);
                    if (response.ok) {
                        return response.json();
                    } else if (response.status === 404) {
                        // 如果链接不存在，设置默认值
                        return {
                            fileName: 'stock-trading-data.zip',
                            link: '',
                            code: ''
                        };
                    } else if (response.status === 401) {
                        // 未登录或会话过期
                        showResult('请先登录或刷新页面后重试', false);
                        throw new Error('未登录或会话已过期');
                    } else {
                        throw new Error(`获取链接信息失败: ${response.status}`);
                    }
                })
                .then(data => {
                    console.log('获取到链接数据:', data);
                    // 填充表单
                    document.getElementById('fileName').value = data.fileName || 'stock-trading-data.zip';
                    document.getElementById('baiduLink').value = data.link || '';
                    document.getElementById('extractCode').value = data.code || '';
                    
                    // 显示模态框
                    try {
                        console.log('尝试显示模态框...');
                        const modalElement = document.getElementById('updateLinkModal');
                        if (!modalElement) {
                            console.error('未找到模态框元素');
                            return;
                        }
                        
                        // 确保先销毁可能存在的旧实例
                        const existingModal = bootstrap.Modal.getInstance(modalElement);
                        if (existingModal) {
                            existingModal.dispose();
                        }
                        
                        // 创建新实例并显示
                        const modal = new bootstrap.Modal(modalElement);
                        modal.show();
                        console.log('模态框已显示');
                    } catch (error) {
                        console.error('显示模态框失败:', error);
                        alert('显示模态框失败: ' + error.message);
                    }
                })
                .catch(error => {
                    console.error('获取历史日线数据链接失败:', error);
                    if (!error.message.includes('未登录')) {
                        showResult('获取链接信息失败，请稍后再试', false);
                    }
                });
        }
        
        // 更新历史指数数据链接
        function updateIndexDataLink() {
            // 设置模态框标题和类型
            document.getElementById('updateLinkModalLabel').textContent = '更新历史指数数据链接';
            document.getElementById('linkType').value = 'index';
            
            console.log('正在获取历史指数数据链接信息...');
            
            // 获取当前链接信息
            fetch('/api/admin/baidu-links/index')
                .then(response => {
                    console.log('获取链接API响应状态:', response.status);
                    if (response.ok) {
                        return response.json();
                    } else if (response.status === 404) {
                        // 如果链接不存在，设置默认值
                        return {
                            fileName: 'stock-main-index-data.zip',
                            link: '',
                            code: ''
                        };
                    } else if (response.status === 401) {
                        // 未登录或会话过期
                        showResult('请先登录或刷新页面后重试', false);
                        throw new Error('未登录或会话已过期');
                    } else {
                        throw new Error(`获取链接信息失败: ${response.status}`);
                    }
                })
                .then(data => {
                    console.log('获取到链接数据:', data);
                    // 填充表单
                    document.getElementById('fileName').value = data.fileName || 'stock-main-index-data.zip';
                    document.getElementById('baiduLink').value = data.link || '';
                    document.getElementById('extractCode').value = data.code || '';
                    
                    // 显示模态框
                    try {
                        console.log('尝试显示模态框...');
                        const modalElement = document.getElementById('updateLinkModal');
                        if (!modalElement) {
                            console.error('未找到模态框元素');
                            return;
                        }
                        
                        // 确保先销毁可能存在的旧实例
                        const existingModal = bootstrap.Modal.getInstance(modalElement);
                        if (existingModal) {
                            existingModal.dispose();
                        }
                        
                        // 创建新实例并显示
                        const modal = new bootstrap.Modal(modalElement);
                        modal.show();
                        console.log('模态框已显示');
                    } catch (error) {
                        console.error('显示模态框失败:', error);
                        alert('显示模态框失败: ' + error.message);
                    }
                })
                .catch(error => {
                    console.error('获取历史指数数据链接失败:', error);
                    if (!error.message.includes('未登录')) {
                        showResult('获取链接信息失败，请稍后再试', false);
                    }
                });
        }
        
        // 更新财务数据链接
        function updateFinancialDataLink() {
            // 设置模态框标题和类型
            document.getElementById('updateLinkModalLabel').textContent = '更新财务数据链接';
            document.getElementById('linkType').value = 'financial';
            
            console.log('正在获取财务数据链接信息...');
            
            // 获取当前链接信息
            fetch('/api/admin/baidu-links/financial')
                .then(response => {
                    console.log('获取链接API响应状态:', response.status);
                    if (response.ok) {
                        return response.json();
                    } else if (response.status === 404) {
                        // 如果链接不存在，设置默认值
                        return {
                            fileName: 'stock-fin-data-xbx.zip',
                            link: '',
                            code: ''
                        };
                    } else if (response.status === 401) {
                        // 未登录或会话过期
                        showResult('请先登录或刷新页面后重试', false);
                        throw new Error('未登录或会话已过期');
                    } else {
                        throw new Error(`获取链接信息失败: ${response.status}`);
                    }
                })
                .then(data => {
                    console.log('获取到链接数据:', data);
                    // 填充表单
                    document.getElementById('fileName').value = data.fileName || 'stock-fin-data-xbx.zip';
                    document.getElementById('baiduLink').value = data.link || '';
                    document.getElementById('extractCode').value = data.code || '';
                    
                    // 显示模态框
                    try {
                        console.log('尝试显示模态框...');
                        const modalElement = document.getElementById('updateLinkModal');
                        if (!modalElement) {
                            console.error('未找到模态框元素');
                            return;
                        }
                        
                        // 确保先销毁可能存在的旧实例
                        const existingModal = bootstrap.Modal.getInstance(modalElement);
                        if (existingModal) {
                            existingModal.dispose();
                        }
                        
                        // 创建新实例并显示
                        const modal = new bootstrap.Modal(modalElement);
                        modal.show();
                        console.log('模态框已显示');
                    } catch (error) {
                        console.error('显示模态框失败:', error);
                        alert('显示模态框失败: ' + error.message);
                    }
                })
                .catch(error => {
                    console.error('获取财务数据链接失败:', error);
                    if (!error.message.includes('未登录')) {
                        showResult('获取链接信息失败，请稍后再试', false);
                    }
                });
        }
        
        // 设置导航切换
        function setupNavigation() {
            // 仪表盘
            document.getElementById('dashboardLink').addEventListener('click', function(e) {
                e.preventDefault();
                showContent('dashboardContent');
                setActiveLink(this);
            });
            
            // 用户管理
            document.getElementById('usersLink').addEventListener('click', function(e) {
                e.preventDefault();
                showContent('usersContent');
                setActiveLink(this);
                // 加载用户数据
                fetchUsers();
            });
            
            // 帖子管理
            document.getElementById('postsLink').addEventListener('click', function(e) {
                e.preventDefault();
                showContent('postsContent');
                setActiveLink(this);
                // 加载帖子数据
                fetchPosts();
            });
            
            // 举报处理
            document.getElementById('reportsLink').addEventListener('click', function(e) {
                e.preventDefault();
                showContent('reportsContent');
                setActiveLink(this);
                // 加载举报数据
                fetchReports('all');
            });
            
            // 举报过滤器
            document.getElementById('filterAllReports').addEventListener('click', function() {
                fetchReports('all');
                setActiveFilter(this);
            });
            
            document.getElementById('filterPendingReports').addEventListener('click', function() {
                fetchReports('pending');
                setActiveFilter(this);
            });
            
            document.getElementById('filterResolvedReports').addEventListener('click', function() {
                fetchReports('resolved');
                setActiveFilter(this);
            });
            
            document.getElementById('filterRejectedReports').addEventListener('click', function() {
                fetchReports('rejected');
                setActiveFilter(this);
            });
            
            // 刷新举报列表
            document.getElementById('refreshReportsBtn').addEventListener('click', function() {
                const activeFilter = document.querySelector('.btn-group .active');
                let status = 'all';
                if (activeFilter) {
                    if (activeFilter.id === 'filterPendingReports') status = 'pending';
                    else if (activeFilter.id === 'filterResolvedReports') status = 'resolved';
                    else if (activeFilter.id === 'filterRejectedReports') status = 'rejected';
                }
                fetchReports(status);
            });
            
            // 用户搜索
            document.getElementById('userSearchBtn').addEventListener('click', function() {
                const searchTerm = document.getElementById('userSearchInput').value.trim();
                fetchUsers(1, 10, searchTerm);
            });
            
            // 回车键搜索
            document.getElementById('userSearchInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    document.getElementById('userSearchBtn').click();
                }
            });
            
            // 刷新用户列表
            document.getElementById('refreshUsersBtn').addEventListener('click', function() {
                fetchUsers();
            });
            
            // 帖子搜索
            document.getElementById('postSearchBtn').addEventListener('click', function() {
                const searchTerm = document.getElementById('postSearchInput').value.trim();
                fetchPosts(1, 10, searchTerm);
            });
            
            // 回车键搜索帖子
            document.getElementById('postSearchInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    document.getElementById('postSearchBtn').click();
                }
            });
            
            // 刷新帖子列表
            document.getElementById('refreshPostsBtn').addEventListener('click', function() {
                fetchPosts();
            });
            
            // 提交处罚表单
            document.getElementById('submitPunishment').addEventListener('click', function() {
                const form = document.getElementById('punishmentForm');
                if (form.checkValidity()) {
                    submitPunishment();
                } else {
                    form.reportValidity();
                }
            });
        }
        
        // 显示内容
        function showContent(contentId) {
            // 隐藏所有内容
            document.querySelectorAll('main > div > div[id$="Content"]').forEach(el => {
                el.style.display = 'none';
            });
            
            // 显示选中的内容
            document.getElementById(contentId).style.display = 'block';
            
            // 确保刷新按钮功能正常工作
            if (contentId === 'usersContent') {
                // 重新绑定用户刷新按钮事件
                const refreshUsersBtn = document.getElementById('refreshUsersBtn');
                if (refreshUsersBtn) {
                    // 移除所有现有的事件监听器
                    const newRefreshBtn = refreshUsersBtn.cloneNode(true);
                    refreshUsersBtn.parentNode.replaceChild(newRefreshBtn, refreshUsersBtn);
                    
                    // 添加新的事件监听器
                    newRefreshBtn.addEventListener('click', function() {
                        console.log('刷新用户列表');
                        fetchUsers();
                        showResult('用户列表已刷新', true);
                    });
                }
            } else if (contentId === 'postsContent') {
                // 重新绑定帖子刷新按钮事件
                const refreshPostsBtn = document.getElementById('refreshPostsBtn');
                if (refreshPostsBtn) {
                    // 移除所有现有的事件监听器
                    const newRefreshBtn = refreshPostsBtn.cloneNode(true);
                    refreshPostsBtn.parentNode.replaceChild(newRefreshBtn, refreshPostsBtn);
                    
                    // 添加新的事件监听器
                    newRefreshBtn.addEventListener('click', function() {
                        console.log('刷新帖子列表');
                        fetchPosts();
                        showResult('帖子列表已刷新', true);
                    });
                }
            } else if (contentId === 'reportsContent') {
                // 重新绑定举报刷新按钮事件
                const refreshReportsBtn = document.getElementById('refreshReportsBtn');
                if (refreshReportsBtn) {
                    // 移除所有现有的事件监听器
                    const newRefreshBtn = refreshReportsBtn.cloneNode(true);
                    refreshReportsBtn.parentNode.replaceChild(newRefreshBtn, refreshReportsBtn);
                    
                    // 添加新的事件监听器
                    newRefreshBtn.addEventListener('click', function() {
                        console.log('刷新举报列表');
                        const activeFilter = document.querySelector('.btn-group .active');
                        let status = 'all';
                        if (activeFilter) {
                            if (activeFilter.id === 'filterPendingReports') status = 'pending';
                            else if (activeFilter.id === 'filterResolvedReports') status = 'resolved';
                            else if (activeFilter.id === 'filterRejectedReports') status = 'rejected';
                        }
                        fetchReports(status);
                        showResult('举报列表已刷新', true);
                    });
                }
            }
        }
        
        // 设置活动链接
        function setActiveLink(link) {
            // 移除所有活动类
            document.querySelectorAll('.sidebar .nav-link').forEach(el => {
                el.classList.remove('active');
            });
            
            // 添加活动类到当前链接
            link.classList.add('active');
        }
        
        // 设置活动过滤器
        function setActiveFilter(button) {
            // 移除所有活动类
            document.querySelectorAll('.btn-group .btn').forEach(el => {
                el.classList.remove('active');
            });
            
            // 添加活动类到当前按钮
            button.classList.add('active');
        }
        
        // 获取用户数据
        function fetchUsers(page = 1, pageSize = 10) {
            const tableBody = document.getElementById('usersTableBody');
            tableBody.innerHTML = '<tr><td colspan="6" class="text-center">正在加载数据...</td></tr>';
            
            const url = `/api/admin/users?page=${page}&pageSize=${pageSize}`;
            
            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取用户数据失败');
                    }
                    return response.json();
                })
                .then(data => {
                    tableBody.innerHTML = '';
                    
                    if (data.users.length === 0) {
                        tableBody.innerHTML = '<tr><td colspan="6" class="text-center">暂无用户数据</td></tr>';
                        return;
                    }
                    
                    data.users.forEach(user => {
                        // 根据状态设置不同的样式和按钮
                        let statusBadge = '';
                        let actionButton = '';
                        
                        if (user.status === '正常') {
                            statusBadge = `<span class="badge bg-success">正常</span>`;
                            actionButton = `<button class="btn btn-sm btn-outline-warning punish-user-btn" data-user-id="${user.id}" data-username="${user.username}" data-status="normal">处罚</button>`;
                        } else if (user.status === '已禁言') {
                            statusBadge = `<span class="badge bg-warning">已禁言</span>`;
                            actionButton = `<button class="btn btn-sm btn-outline-success punish-user-btn" data-user-id="${user.id}" data-username="${user.username}" data-status="muted">解禁</button>`;
                        } else if (user.status === '已封禁') {
                            statusBadge = `<span class="badge bg-danger">已封禁</span>`;
                            actionButton = `<button class="btn btn-sm btn-outline-success punish-user-btn" data-user-id="${user.id}" data-username="${user.username}" data-status="banned">解禁</button>`;
                        } else {
                            statusBadge = `<span class="badge bg-secondary">${user.status}</span>`;
                            actionButton = `<button class="btn btn-sm btn-outline-warning punish-user-btn" data-user-id="${user.id}" data-username="${user.username}" data-status="other">处罚</button>`;
                        }
                        
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${user.id}</td>
                            <td>${user.username}</td>
                            <td>${new Date(user.createdAt).toLocaleString()}</td>
                            <td>${user.lastLogin ? new Date(user.lastLogin).toLocaleString() : '从未登录'}</td>
                            <td>${statusBadge}</td>
                            <td>${actionButton}</td>
                        `;
                        tableBody.appendChild(row);
                    });
                    
                    document.querySelectorAll('.punish-user-btn').forEach(btn => {
                        btn.addEventListener('click', function() {
                            const userId = this.getAttribute('data-user-id');
                            const username = this.getAttribute('data-username');
                            const status = this.getAttribute('data-status');
                            showSimpleUserPunishModal(null, userId, username, status);
                        });
                    });
                    
                    // 创建分页控件
                    const pagination = document.getElementById('usersPagination');
                    pagination.innerHTML = '';
                    
                    // 添加上一页按钮
                    const prevLi = document.createElement('li');
                    prevLi.className = `page-item ${page === 1 ? 'disabled' : ''}`;
                    prevLi.innerHTML = `<a class="page-link" href="#" data-page="${page-1}">上一页</a>`;
                    pagination.appendChild(prevLi);
                    
                    // 添加页码按钮
                    const totalPages = data.totalPages;
                    let startPage = Math.max(1, page - 2);
                    let endPage = Math.min(totalPages, page + 2);
                    
                    if (endPage - startPage < 4 && totalPages > 5) {
                        if (startPage === 1) {
                            endPage = Math.min(startPage + 4, totalPages);
                        } else if (endPage === totalPages) {
                            startPage = Math.max(endPage - 4, 1);
                        }
                    }
                    
                    for (let i = startPage; i <= endPage; i++) {
                        const pageLi = document.createElement('li');
                        pageLi.className = `page-item ${i === page ? 'active' : ''}`;
                        pageLi.innerHTML = `<a class="page-link" href="#" data-page="${i}">${i}</a>`;
                        pagination.appendChild(pageLi);
                    }
                    
                    // 添加下一页按钮
                    const nextLi = document.createElement('li');
                    nextLi.className = `page-item ${page === totalPages ? 'disabled' : ''}`;
                    nextLi.innerHTML = `<a class="page-link" href="#" data-page="${page+1}">下一页</a>`;
                    pagination.appendChild(nextLi);
                    
                    // 添加分页事件监听器
                    document.querySelectorAll('#usersPagination .page-link').forEach(link => {
                        link.addEventListener('click', function(e) {
                            e.preventDefault();
                            const nextPage = parseInt(this.getAttribute('data-page'));
                            if (nextPage > 0 && nextPage <= totalPages) {
                                fetchUsers(nextPage, pageSize);
                            }
                        });
                    });
                })
                .catch(error => {
                    console.error('获取用户数据失败:', error);
                    tableBody.innerHTML = `
                        <tr><td colspan="6" class="text-center text-danger">获取数据失败，请重试</td></tr>
                    `;
                });
        }
        
        // 显示处罚模态框
        function showPunishmentModal(reportId, userId, username) {
            console.log('显示处罚模态框:', { reportId, userId, username });
            
            // 设置隐藏字段的值
            document.getElementById('punishUserId').value = userId;
            document.getElementById('punishReportId').value = reportId || '';
            
            // 重置表单
            document.getElementById('punishmentForm').reset();
            
            // 更新模态框标题，显示用户信息
            const modalTitle = document.getElementById('punishmentModalLabel');
            if (username) {
                modalTitle.textContent = `处罚用户: ${username} (ID: ${userId})`;
            } else {
                // 如果没有提供用户名，尝试获取用户信息
                fetch(`/api/admin/users/${userId}`)
                    .then(response => {
                        if (response.ok) {
                            return response.json();
                        } else {
                            throw new Error('获取用户信息失败');
                        }
                    })
                    .then(user => {
                        modalTitle.textContent = `处罚用户: ${user.username} (ID: ${userId})`;
                    })
                    .catch(error => {
                        console.error('获取用户信息失败:', error);
                        modalTitle.textContent = `处罚用户 (ID: ${userId})`;
                    });
            }
            
            // 如果是来自举报的处罚，获取举报信息并设置默认处罚原因
            if (reportId) {
                fetch(`/api/admin/reports/${reportId}`)
                    .then(response => {
                        if (response.ok) {
                            return response.json();
                        } else {
                            throw new Error('获取举报信息失败');
                        }
                    })
                    .then(report => {
                        // 设置默认处罚原因，基于举报原因和帖子ID
                        const reasonField = document.getElementById('reason');
                        reasonField.value = `处理举报 #${reportId} (帖子ID: ${report.postId}): ${report.reason || '违反社区规则'}`;
                        
                        // 可以在这里添加隐藏字段存储帖子ID，如果后端API需要
                        if (document.getElementById('punishPostId')) {
                            document.getElementById('punishPostId').value = report.postId;
                        } else {
                            // 如果表单中没有这个字段，可以在此动态创建
                            const postIdField = document.createElement('input');
                            postIdField.type = 'hidden';
                            postIdField.id = 'punishPostId';
                            postIdField.name = 'postId';
                            postIdField.value = report.postId;
                            document.getElementById('punishmentForm').appendChild(postIdField);
                        }
                    })
                    .catch(error => {
                        console.error('获取举报信息失败:', error);
                    });
            }
            
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('punishmentModal'));
            modal.show();
        }
        
        // 提交处罚
        function submitPunishment() {
            // 收集表单数据
            const userId = document.getElementById('punishUserId').value;
            const reportId = document.getElementById('punishReportId').value;
            const punishmentType = document.getElementById('punishmentType').value;
            const durationDays = document.getElementById('durationDays').value;
            const reason = document.getElementById('reason').value;
            
            // 获取帖子ID（如果存在）
            const postIdField = document.getElementById('punishPostId');
            const postId = postIdField ? postIdField.value : null;
            
            console.log('提交处罚数据:', {
                userId,
                reportId,
                postId,
                punishmentType,
                durationDays,
                reason
            });
            
            // 构建要发送的数据
            const formData = new FormData();
            formData.append('userId', userId);
            formData.append('punishmentType', punishmentType);
            formData.append('durationDays', durationDays);
            formData.append('reason', reason);
            
            // 如果有关联的举报ID，添加到表单数据
            if (reportId) {
                formData.append('reportId', reportId);
            }
            
            // 如果有关联的帖子ID，添加到表单数据
            if (postId) {
                formData.append('postId', postId);
            }
            
            // 显示加载中消息
            showResult('正在提交处罚...', true);
            
            // 发送请求到后端API
            fetch('/api/admin/punishments', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    // 尝试获取错误详情
                    return response.text().then(text => {
                        try {
                            const errorData = JSON.parse(text);
                            throw new Error(errorData.message || '处罚提交失败');
                        } catch (e) {
                            throw new Error(`处罚提交失败: ${response.status} ${response.statusText}`);
                        }
                    });
                }
                return response.json();
            })
            .then(data => {
                console.log('处罚提交成功:', data);
                
                // 如果有关联的举报ID，更新举报状态为已处理
                if (reportId) {
                    return updateReportStatus(reportId, 'resolved')
                        .then(() => data);
                }
                return data;
            })
            .then(data => {
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('punishmentModal'));
                modal.hide();
                
                // 显示成功消息
                showResult(data.message || '处罚已成功提交', true);
                
                // 刷新举报列表和用户列表
                document.getElementById('refreshReportsBtn').click();
                // 如果用户管理页面是活跃的，也刷新用户列表
                if (document.getElementById('usersContent').style.display !== 'none') {
                    document.getElementById('refreshUsersBtn').click();
                }
            })
            .catch(error => {
                console.error('提交处罚失败:', error);
                showResult(error.message || '处罚提交失败，请重试', false);
            });
        }
        
        // 更新举报状态
        function updateReportStatus(reportId, status) {
            console.log(`更新举报 #${reportId} 状态为 ${status}`);
            
            return fetch(`/api/admin/reports/${reportId}/status`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    'status': status
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`更新举报状态失败: ${response.status} ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('举报状态更新成功:', data);
                return data;
            })
            .catch(error => {
                console.error('更新举报状态失败:', error);
                throw error; // 继续向上传播错误
            });
        }
        
        // 获取帖子数据
        function fetchPosts(page = 1, pageSize = 10) {
            const tableBody = document.getElementById('postsTableBody');
            tableBody.innerHTML = '<tr><td colspan="6" class="text-center">正在加载数据...</td></tr>';
            
            const url = `/api/admin/posts?page=${page}&pageSize=${pageSize}`;
            
            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取帖子数据失败');
                    }
                    return response.json();
                })
                .then(data => {
                    tableBody.innerHTML = '';
                    
                    if (data.posts.length === 0) {
                        tableBody.innerHTML = '<tr><td colspan="6" class="text-center">暂无帖子数据</td></tr>';
                        return;
                    }
                    
                    data.posts.forEach(post => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${post.id}</td>
                            <td>${post.title}</td>
                            <td>${post.username || `用户#${post.userId}`}</td>
                            <td>${new Date(post.createdAt).toLocaleString()}</td>
                            <td><span class="badge bg-info">${post.commentCount}</span> / <span class="badge bg-primary">${post.likeCount}</span></td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary view-post-btn" data-post-id="${post.id}">查看</button>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                    
                    // 添加事件监听器
                    document.querySelectorAll('.view-post-btn').forEach(btn => {
                        btn.addEventListener('click', function() {
                            const postId = this.getAttribute('data-post-id');
                            viewPost(postId);
                        });
                    });
                    
                    // 创建分页控件
                    const pagination = document.getElementById('postsPagination');
                    pagination.innerHTML = '';
                    
                    // 添加上一页按钮
                    const prevLi = document.createElement('li');
                    prevLi.className = `page-item ${page === 1 ? 'disabled' : ''}`;
                    prevLi.innerHTML = `<a class="page-link" href="#" data-page="${page-1}">上一页</a>`;
                    pagination.appendChild(prevLi);
                    
                    // 添加页码按钮
                    const totalPages = data.totalPages;
                    let startPage = Math.max(1, page - 2);
                    let endPage = Math.min(totalPages, page + 2);
                    
                    if (endPage - startPage < 4 && totalPages > 5) {
                        if (startPage === 1) {
                            endPage = Math.min(startPage + 4, totalPages);
                        } else if (endPage === totalPages) {
                            startPage = Math.max(endPage - 4, 1);
                        }
                    }
                    
                    for (let i = startPage; i <= endPage; i++) {
                        const pageLi = document.createElement('li');
                        pageLi.className = `page-item ${i === page ? 'active' : ''}`;
                        pageLi.innerHTML = `<a class="page-link" href="#" data-page="${i}">${i}</a>`;
                        pagination.appendChild(pageLi);
                    }
                    
                    // 添加下一页按钮
                    const nextLi = document.createElement('li');
                    nextLi.className = `page-item ${page === totalPages ? 'disabled' : ''}`;
                    nextLi.innerHTML = `<a class="page-link" href="#" data-page="${page+1}">下一页</a>`;
                    pagination.appendChild(nextLi);
                    
                    // 添加分页事件监听器
                    document.querySelectorAll('#postsPagination .page-link').forEach(link => {
                        link.addEventListener('click', function(e) {
                            e.preventDefault();
                            const nextPage = parseInt(this.getAttribute('data-page'));
                            if (nextPage > 0 && nextPage <= totalPages) {
                                fetchPosts(nextPage, pageSize);
                            }
                        });
                    });
                })
                .catch(error => {
                    console.error('获取帖子数据失败:', error);
                    tableBody.innerHTML = `
                        <tr><td colspan="6" class="text-center text-danger">获取数据失败，请重试</td></tr>
                    `;
                });
        }
        
        // 查看帖子
        function viewPost(postId) {
            // 显示加载中
            document.getElementById('post-title').textContent = '加载中...';
            document.getElementById('post-author').textContent = '';
            document.getElementById('post-date').textContent = '';
            document.getElementById('post-views').textContent = '0';
            document.getElementById('post-comments').textContent = '0';
            document.getElementById('post-likes').textContent = '0';
            document.getElementById('post-content-text').textContent = '';
            document.getElementById('post-images').innerHTML = '';
            document.getElementById('post-tags-container').innerHTML = '';
            
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('postDetailModal'));
            modal.show();
            
            // 获取帖子详情
            console.log('查看帖子ID:', postId);
            fetch(`/api/admin/posts/${postId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取帖子详情失败');
                    }
                    return response.json();
                })
                .then(post => {
                    console.log('获取到帖子数据:', post);
                    
                    // 更新模态框内容
                    document.getElementById('post-title').textContent = post.title || '无标题';
                    document.getElementById('post-author').textContent = post.username || '匿名用户';
                    document.getElementById('post-date').textContent = post.createdAt ? new Date(post.createdAt).toLocaleString() : '未知时间';
                    document.getElementById('post-views').textContent = post.viewCount || 0;
                    document.getElementById('post-comments').textContent = post.commentCount || 0;
                    document.getElementById('post-likes').textContent = post.likeCount || 0;
                    
                    // 处理内容，保留换行
                    const contentElement = document.getElementById('post-content-text');
                    contentElement.innerHTML = '';
                    
                    // 将内容按行分割并添加到DOM中
                    if (post.content) {
                    const lines = post.content.split('\n');
                    lines.forEach(line => {
                        const p = document.createElement('p');
                        p.textContent = line;
                        contentElement.appendChild(p);
                    });
                    } else {
                        const p = document.createElement('p');
                        p.textContent = '该帖子没有内容';
                        p.className = 'text-muted';
                        contentElement.appendChild(p);
                    }
                    
                    // 处理图片
                    const imagesContainer = document.getElementById('post-images');
                    imagesContainer.innerHTML = '';
                    
                    if (post.images && post.images.length > 0) {
                        post.images.forEach(image => {
                            const imgWrapper = document.createElement('div');
                            imgWrapper.className = 'image-wrapper';
                            
                            const img = document.createElement('img');
                            
                            // 修正图片路径，处理不同格式的URL
                            let imagePath = image.imagePath;
                            
                            // 检查是否包含完整URL
                            if (imagePath) {
                                // 方法1: 如果包含特定端口，替换为正确端口
                                if (imagePath.includes('localhost:8002')) {
                                    imagePath = imagePath.replace('localhost:8002', 'localhost');
                                }
                                
                                // 方法2: 如果是相对路径，转换为绝对路径
                                if (imagePath.startsWith('/static')) {
                                    imagePath = 'http://localhost' + imagePath;
                                }
                                
                                // 方法3: 如果只有文件名，构建完整路径
                                if (!imagePath.includes('/') && !imagePath.startsWith('http')) {
                                    imagePath = 'http://localhost/static/uploads/forum/' + imagePath;
                                }
                                
                                // 记录最终使用的图片路径
                                console.log('使用图片路径:', imagePath);
                            }
                            
                            img.src = imagePath || '';
                            img.className = 'img-thumbnail';
                            img.style.maxHeight = '200px';
                            img.alt = '帖子图片';
                            
                            // 添加加载错误处理
                            img.onerror = function() {
                                console.error('图片加载失败:', imagePath);
                                this.src = '/static/images/image-not-found.png';
                                this.alt = '图片加载失败';
                            };
                            
                            imgWrapper.appendChild(img);
                            imagesContainer.appendChild(imgWrapper);
                        });
                    }
                    
                    // 处理标签
                    const tagsContainer = document.getElementById('post-tags-container');
                    tagsContainer.innerHTML = '';
                    
                    if (post.tags && post.tags.length > 0) {
                        post.tags.forEach(tag => {
                            const tagSpan = document.createElement('span');
                            tagSpan.className = 'badge bg-secondary me-1';
                            tagSpan.textContent = tag;
                            tagsContainer.appendChild(tagSpan);
                        });
                    } else {
                        tagsContainer.textContent = '无标签';
                    }
                    
                    // 处理评论
                    const commentsContainer = document.getElementById('post-comments-container');
                    commentsContainer.innerHTML = '';
                    
                    if (post.comments && post.comments.length > 0) {
                        post.comments.forEach(comment => {
                            const commentDiv = document.createElement('div');
                            commentDiv.className = 'comment-item mb-3 p-3 border-bottom';
                            
                            commentDiv.innerHTML = `
                                <div class="d-flex justify-content-between mb-2">
                                    <div class="comment-author">
                                        <strong>用户ID: ${comment.userId}</strong>
                                    </div>
                                    <div class="comment-date text-muted">
                                        ${new Date(comment.createdAt).toLocaleString()}
                                    </div>
                                </div>
                                <div class="comment-content">
                                    ${comment.content}
                                </div>
                            `;
                            
                            commentsContainer.appendChild(commentDiv);
                        });
                    } else {
                        commentsContainer.innerHTML = '<p class="text-muted">暂无评论</p>';
                    }
                })
                .catch(error => {
                    console.error('获取帖子详情失败:', error);
                    document.getElementById('post-title').textContent = '加载失败';
                    document.getElementById('post-content-text').textContent = '获取帖子详情失败，请重试';
                });
        }
        
        // 获取举报数据
        function fetchReports(status = 'all', page = 1, pageSize = 10) {
            fetch(`/api/admin/reports?status=${status}&page=${page}&pageSize=${pageSize}`)
                .then(response => response.json())
                .then(reports => {
                    const tableBody = document.getElementById('reportsTableBody');
                    tableBody.innerHTML = '';
                    
                    if (reports.length === 0) {
                        tableBody.innerHTML = `<tr><td colspan="7" class="text-center">暂无举报数据</td></tr>`;
                        return;
                    }
                    
                    reports.forEach(report => {
                        const row = document.createElement('tr');
                        
                        // 根据状态设置不同的样式
                        let statusBadge = '';
                        if (report.status === 'pending') {
                            statusBadge = `<span class="badge bg-warning">待处理</span>`;
                        } else if (report.status === 'resolved') {
                            statusBadge = `<span class="badge bg-success">已处理</span>`;
                        } else if (report.status === 'rejected') {
                            statusBadge = `<span class="badge bg-secondary">已驳回</span>`;
                        }
                        
                        // 根据状态显示不同的操作按钮
                        let actionButtons = '';
                        if (report.status === 'pending') {
                            actionButtons = `
                                <button class="btn btn-sm btn-outline-primary view-post-btn" data-post-id="${report.postId}">查看帖子</button>
                                <button class="btn btn-sm btn-outline-success resolve-btn" data-report-id="${report.id}" data-post-id="${report.postId}">处理</button>
                                <button class="btn btn-sm btn-outline-secondary reject-btn" data-report-id="${report.id}">驳回</button>
                            `;
                        } else {
                            actionButtons = `<button class="btn btn-sm btn-outline-primary view-post-btn" data-post-id="${report.postId}">查看帖子</button>`;
                        }
                        
                        row.innerHTML = `
                            <td>${report.id}</td>
                            <td>${report.postId}</td>
                            <td>${report.username || `用户#${report.userId}`}</td>
                            <td>${report.reason}</td>
                            <td>${new Date(report.createdAt).toLocaleString()}</td>
                            <td>${statusBadge}</td>
                            <td>${actionButtons}</td>
                        `;
                        tableBody.appendChild(row);
                    });
                    
                    // 添加事件监听器
                    document.querySelectorAll('.view-post-btn').forEach(btn => {
                        btn.addEventListener('click', function() {
                            const postId = this.getAttribute('data-post-id');
                            viewPost(postId);
                        });
                    });
                    
                    document.querySelectorAll('.resolve-btn').forEach(btn => {
                        btn.addEventListener('click', function() {
                            const reportId = this.getAttribute('data-report-id');
                            const postId = this.getAttribute('data-post-id');
                            
                            // 首先获取帖子信息，找到帖子发布者
                            fetch(`/api/admin/posts/${postId}`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                }
                            })
                            .then(response => {
                                if (!response.ok) {
                                    throw new Error('获取帖子信息失败');
                                }
                                return response.json();
                            })
                            .then(post => {
                                console.log('获取到帖子数据:', post);
                                // 使用帖子作者的ID和用户名
                                const postAuthorId = post.userId;
                                const postAuthorName = post.username;
                                
                                if (!postAuthorId) {
                                    throw new Error('无法确定帖子作者');
                                }
                                
                                // 查询用户状态
                                return fetch(`/api/admin/users/${postAuthorId}`)
                                    .then(response => {
                                        if (!response.ok) {
                                            throw new Error('获取用户状态失败');
                                        }
                                        return response.json();
                                    })
                                    .then(userData => {
                                        console.log('获取到用户状态:', userData);
                                        
                                        let userStatus = 'normal';
                                        if (userData.status === '已禁言') {
                                            userStatus = 'muted';
                                        } else if (userData.status === '已封禁') {
                                            userStatus = 'banned';
                                        }
                                        
                                        // 使用简化的处理模态框，并传递用户状态
                                        if (userStatus === 'muted' || userStatus === 'banned') {
                                            // 如果用户已经被处罚，询问是否要解禁
                                            showSimpleUserPunishModal(reportId, postAuthorId, postAuthorName, userStatus);
                                        } else {
                                            // 正常状态用户展示处罚选项
                                            showSimpleReportHandleModal(reportId, postId, postAuthorId, postAuthorName);
                                        }
                                    });
                            })
                            .catch(error => {
                                console.error('获取帖子作者信息失败:', error);
                                showResult('获取帖子作者信息失败，请重试', false);
                            });
                        });
                    });
                    
                    document.querySelectorAll('.reject-btn').forEach(btn => {
                        btn.addEventListener('click', function() {
                            const reportId = this.getAttribute('data-report-id');
                            console.log('驳回按钮被点击，举报ID:', reportId);
                            
                            // 存储举报ID到全局变量
                            currentReportId = reportId;
                            
                            // 显示模态框
                            const confirmRejectReportModal = new bootstrap.Modal(document.getElementById('confirmRejectReportModal'));
                            confirmRejectReportModal.show();
                        });
                    });
                    
                    // 创建分页控件
                    // 这里简化处理，实际应该根据总记录数和当前页码创建
                    const pagination = document.getElementById('reportsPagination');
                    pagination.innerHTML = `
                        <li class="page-item ${page === 1 ? 'disabled' : ''}">
                            <a class="page-link" href="#" data-page="${page-1}">上一页</a>
                        </li>
                        <li class="page-item active">
                            <a class="page-link" href="#" data-page="${page}">${page}</a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="#" data-page="${page+1}">下一页</a>
                        </li>
                    `;
                    
                    // 添加分页事件监听器
                    document.querySelectorAll('#reportsPagination .page-link').forEach(link => {
                        link.addEventListener('click', function(e) {
                            e.preventDefault();
                            const nextPage = parseInt(this.getAttribute('data-page'));
                            if (nextPage > 0) {
                                fetchReports(status, nextPage, pageSize);
                            }
                        });
                    });
                })
                .catch(error => {
                    console.error('获取举报数据失败:', error);
                    document.getElementById('reportsTableBody').innerHTML = `
                        <tr><td colspan="7" class="text-center text-danger">获取数据失败，请重试</td></tr>
                    `;
                });
        }
        
        // 驳回举报
        function rejectReport(reportId) {
            console.log(`驳回举报 #${reportId}`);
            
            // 显示加载中消息
            showResult('正在处理...', true);
            
            // 发送请求到API
            fetch(`/api/admin/reports/${reportId}/status`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    'status': 'rejected'
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`更新举报状态失败: ${response.status} ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('驳回举报成功:', data);
                
                // 显示成功消息
                showResult(data.message || '举报已驳回', true);
                
                // 刷新举报列表
                document.getElementById('refreshReportsBtn').click();
                
                // 更新仪表盘统计数据
                fetchStatistics();
            })
            .catch(error => {
                console.error('驳回举报失败:', error);
                showResult(error.message || '驳回举报失败，请重试', false);
            });
        }
        
        // 删除帖子
        function deletePost(postId) {
            console.log(`删除帖子 #${postId}`);
            
            // 显示加载中消息
            showResult('正在删除帖子...', true);
            
            // 发送请求到API
            fetch(`/api/admin/posts/${postId}`, {
                method: 'DELETE'
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`删除帖子失败: ${response.status} ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('删除帖子成功:', data);
                
                // 显示成功消息
                showResult(data.message || '帖子已成功删除', true);
                
                // 刷新帖子列表
                if (document.getElementById('postsContent').style.display !== 'none') {
                    document.getElementById('refreshPostsBtn').click();
                }
                
                // 如果在举报页面，也刷新举报列表
                if (document.getElementById('reportsContent').style.display !== 'none') {
                    document.getElementById('refreshReportsBtn').click();
                }
            })
            .catch(error => {
                console.error('删除帖子失败:', error);
                showResult(error.message || '删除帖子失败，请重试', false);
            });
        }
        
        // 全局变量，用于存储当前处理的举报ID
        let currentReportId = null;
        
        // 处理驳回举报
        function handleRejectReport() {
            console.log('处理驳回举报，当前举报ID:', currentReportId);
            
            if (!currentReportId) {
                console.error('未能获取举报ID，无法驳回举报');
                showResult('未能获取举报ID，无法驳回举报', false);
                return;
            }
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('confirmRejectReportModal'));
            if (modal) {
                modal.hide();
            }
            
            // 调用驳回举报函数
            rejectReport(currentReportId);
            
            // 重置当前举报ID
            currentReportId = null;
        }
        
        // 显示简化的举报处理模态框
        function showSimpleReportHandleModal(reportId, postId, userId, username) {
            console.log('显示简化的举报处理模态框:', { reportId, postId, userId, username });
            
            // 设置模态框数据
            document.getElementById('reportUserName').textContent = username || '未知用户';
            document.getElementById('reportUserId').textContent = userId;
            document.getElementById('simpleReportId').value = reportId;
            document.getElementById('simplePostId').value = postId;
            
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('simpleReportHandleModal'));
            modal.show();
            
            // 设置按钮事件
            document.getElementById('muteUserBtn').onclick = function() {
                handlePunishUser(reportId, userId, 'mute');
                modal.hide();
            };
            
            document.getElementById('banUserBtn').onclick = function() {
                handlePunishUser(reportId, userId, 'ban');
                modal.hide();
            };
        }
        
        // 处理举报操作（禁言或封禁）
        function handleReportAction(reportId, userId, action) {
            console.log(`处理举报 #${reportId}，对用户 #${userId} 进行 ${action} 操作`);
            
            // 显示加载中消息
            showResult('正在处理...', true);
            
            // 准备请求数据
            const formData = new FormData();
            formData.append('userId', userId);
            formData.append('punishmentType', action);
            formData.append('durationDays', 7); // 固定设为7天
            formData.append('reason', `处理举报 #${reportId}`);
            
            if (reportId) {
                formData.append('reportId', reportId); // 服务器端期望的参数名可能是reportId
                // 为确保兼容性，也添加relatedReportId参数
                formData.append('relatedReportId', reportId);
            }
            
            // 记录发送的数据
            console.log('发送处罚请求数据:', {
                userId,
                punishmentType: action,
                durationDays: 7,
                reason: `处理举报 #${reportId}`,
                reportId,
                relatedReportId: reportId
            });
            
            // 发送请求到API
            fetch('/api/admin/punishments', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                console.log('处罚API响应状态:', response.status);
                if (!response.ok) {
                    return response.text().then(text => {
                        console.error('处罚API错误响应:', text);
                        try {
                            const errorData = JSON.parse(text);
                            throw new Error(errorData.message || errorData.detail || '处罚提交失败');
                        } catch (e) {
                            throw new Error(`处罚提交失败: ${response.status} ${response.statusText}`);
                        }
                    });
                }
                return response.json();
            })
            .then(data => {
                console.log('处罚提交成功:', data);
                
                // 更新举报状态为已处理
                return updateReportStatus(reportId, 'resolved')
                    .then(() => data);
            })
            .then(data => {
                // 显示成功消息
                showResult(data.message || `成功${action === 'mute' ? '禁言' : '封禁'}用户`, true);
                
                // 刷新举报列表
                document.getElementById('refreshReportsBtn').click();
                
                // 更新仪表盘统计数据
                fetchStatistics();
            })
            .catch(error => {
                console.error('提交处罚失败:', error);
                showResult(error.message || '处罚提交失败，请重试', false);
            });
        }
        
        // 处理提交更新链接
        function handleSubmitUpdateLink() {
            console.log('handleSubmitUpdateLink被调用');
            
            // 检查会话状态
            fetch('/api/admin/info')
                .then(response => {
                    console.log('会话检查响应状态:', response.status);
                    if (!response.ok) {
                        alert('会话状态异常，可能未登录或会话已过期。请尝试刷新页面并重新登录。');
                        throw new Error('会话状态异常');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('当前登录管理员:', data);
                    
                    // 继续提交表单
                    const form = document.getElementById('updateLinkForm');
                    if (form.checkValidity()) {
                        submitUpdateLink();
                    } else {
                        form.reportValidity();
                    }
                })
                .catch(error => {
                    console.error('会话检查失败:', error);
                    showResult('会话检查失败: ' + error.message, false);
                });
        }
        
        // 提交更新链接
        function submitUpdateLink() {
            // 获取表单数据
            const type = document.getElementById('linkType').value;
            const fileName = document.getElementById('fileName').value;
            const link = document.getElementById('baiduLink').value;
            const code = document.getElementById('extractCode').value;
            
            console.log('准备提交链接数据:', { type, fileName, link, code });
            
            // 验证链接格式
            if (!link.startsWith('https://pan.baidu.com/s/')) {
                showResult('请输入正确的百度网盘链接格式', false);
                return;
            }
            
            // 验证提取码
            if (code.length !== 4) {
                showResult('提取码应为4位字符', false);
                return;
            }
            
            // 显示加载中消息
            showResult('正在更新链接...', true);
            
            // 准备表单数据
            const formData = new FormData();
            formData.append('type', type);
            formData.append('fileName', fileName);
            formData.append('link', link);
            formData.append('code', code);
            
            console.log('发送更新链接请求...');
            
            // 发送请求
            fetch('/api/admin/baidu-links/update', {
                method: 'POST',
                body: formData,
                credentials: 'include' // 确保包含cookies
            })
            .then(response => {
                console.log('更新链接API响应状态:', response.status);
                if (!response.ok) {
                    return response.text().then(text => {
                        console.error('响应内容:', text);
                        throw new Error(`更新链接失败: ${response.status} ${response.statusText}`);
                    });
                }
                return response.json();
            })
            .then(data => {
                console.log('更新链接成功:', data);
                
                try {
                    // 获取模态框实例
                    const modalElement = document.getElementById('updateLinkModal');
                    const modalInstance = bootstrap.Modal.getInstance(modalElement);
                    
                    // 关闭模态框
                    if (modalInstance) {
                        console.log('关闭模态框...');
                        modalInstance.hide();
                        
                        // 确保背景遮罩被移除
                        setTimeout(() => {
                            const backdrops = document.querySelectorAll('.modal-backdrop');
                            backdrops.forEach(backdrop => {
                                backdrop.classList.remove('show');
                                backdrop.classList.remove('fade');
                                backdrop.remove();
                            });
                            document.body.classList.remove('modal-open');
                            document.body.style.overflow = '';
                            document.body.style.paddingRight = '';
                        }, 300);
                    } else {
                        console.warn('未找到模态框实例');
                    }
                } catch (error) {
                    console.error('关闭模态框失败:', error);
                }
                
                // 显示成功消息
                showResult(data.message || '链接已成功更新', true);
            })
            .catch(error => {
                console.error('更新链接失败:', error);
                showResult('更新链接失败: ' + error.message, false);
            });
        }
        
        // 显示简化的用户处罚模态框
        function showSimpleUserPunishModal(reportId, userId, username, status) {
            console.log('显示简化的用户处罚模态框:', { reportId, userId, username, status });
            
            // 根据用户状态设置不同的模态框内容
            if (status === 'muted' || status === 'banned') {
                // 解禁模式
                document.getElementById('simpleUserPunishModal').querySelector('.modal-header').classList.remove('bg-warning');
                document.getElementById('simpleUserPunishModal').querySelector('.modal-header').classList.add('bg-success');
                document.getElementById('simpleUserPunishModalLabel').textContent = '解除用户处罚';
                
                // 设置模态框数据
                document.getElementById('punishUserName').textContent = username || '未知用户';
                document.getElementById('punishUserId').textContent = userId;
                
                // 更新提示文字
                document.querySelector('#simpleUserPunishModal .modal-body p').innerHTML = 
                    `确定要解除对用户 <strong id="punishUserName">${username || '未知用户'}</strong> (ID: <span id="punishUserId">${userId}</span>) 的${status === 'muted' ? '禁言' : '封禁'}处罚吗？`;
                
                // 隐藏处罚按钮，显示解禁按钮
                document.getElementById('userMuteBtn').style.display = 'none';
                document.getElementById('userBanBtn').style.display = 'none';
                
                // 创建或更新解禁按钮
                let unpunishBtn = document.getElementById('userUnpunishBtn');
                if (!unpunishBtn) {
                    unpunishBtn = document.createElement('button');
                    unpunishBtn.id = 'userUnpunishBtn';
                    unpunishBtn.className = 'btn btn-success btn-lg';
                    unpunishBtn.innerHTML = '<i class="bi bi-unlock me-2"></i>确认解除处罚';
                    document.querySelector('#simpleUserPunishModal .d-flex.justify-content-center').appendChild(unpunishBtn);
                } else {
                    unpunishBtn.style.display = 'block';
                }
                
                // 设置解禁按钮点击事件
                unpunishBtn.onclick = function() {
                    handleUnpunishUser(userId);
                    bootstrap.Modal.getInstance(document.getElementById('simpleUserPunishModal')).hide();
                };
                
            } else {
                // 处罚模式
                document.getElementById('simpleUserPunishModal').querySelector('.modal-header').classList.remove('bg-success');
                document.getElementById('simpleUserPunishModal').querySelector('.modal-header').classList.add('bg-warning');
                document.getElementById('simpleUserPunishModalLabel').textContent = '处罚用户';
                
                // 设置模态框数据
                document.getElementById('punishUserName').textContent = username || '未知用户';
                document.getElementById('punishUserId').textContent = userId;
                
                // 更新提示文字
                document.querySelector('#simpleUserPunishModal .modal-body p').innerHTML = 
                    `请选择对用户 <strong id="punishUserName">${username || '未知用户'}</strong> (ID: <span id="punishUserId">${userId}</span>) 的处罚操作：`;
                
                // 显示处罚按钮
                document.getElementById('userMuteBtn').style.display = 'block';
                document.getElementById('userBanBtn').style.display = 'block';
                
                // 隐藏解禁按钮（如果存在）
                const unpunishBtn = document.getElementById('userUnpunishBtn');
                if (unpunishBtn) {
                    unpunishBtn.style.display = 'none';
                }
                
                // 设置按钮事件
                document.getElementById('userMuteBtn').onclick = function() {
                    handlePunishUser(reportId, userId, 'mute');
                    bootstrap.Modal.getInstance(document.getElementById('simpleUserPunishModal')).hide();
                };
                
                document.getElementById('userBanBtn').onclick = function() {
                    handlePunishUser(reportId, userId, 'ban');
                    bootstrap.Modal.getInstance(document.getElementById('simpleUserPunishModal')).hide();
                };
            }
            
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('simpleUserPunishModal'));
            modal.show();
        }
        
        // 处理用户解禁
        function handleUnpunishUser(userId) {
            console.log(`解禁用户 #${userId}`);
            
            // 显示加载中消息
            showResult('正在解除处罚...', true);
            
            // 发送请求到API删除处罚记录
            fetch(`/api/admin/punishments/${userId}`, {
                method: 'DELETE'
            })
            .then(response => {
                console.log('解禁API响应状态:', response.status);
                if (!response.ok) {
                    return response.text().then(text => {
                        console.error('解禁API错误响应:', text);
                        try {
                            const errorData = JSON.parse(text);
                            throw new Error(errorData.message || errorData.detail || '解除处罚失败');
                        } catch (e) {
                            throw new Error(`解除处罚失败: ${response.status} ${response.statusText}`);
                        }
                    });
                }
                return response.json();
            })
            .then(data => {
                console.log('解禁成功:', data);
                
                // 显示成功消息
                showResult(data.message || '已成功解除用户处罚', true);
                
                // 刷新用户列表
                document.getElementById('refreshUsersBtn').click();
                
                // 更新仪表盘统计数据
                fetchStatistics();
            })
            .catch(error => {
                console.error('解除处罚失败:', error);
                showResult(error.message || '解除处罚失败，请重试', false);
            });
        }
        
        // 处理用户处罚（禁言或封禁）
        function handlePunishUser(reportId, userId, action) {
            console.log(`处罚用户 #${userId}，执行 ${action} 操作，关联举报ID: ${reportId || '无'}`);
            
            // 显示加载中消息
            showResult('正在执行处罚...', true);
            
            // 准备请求数据
            const formData = new FormData();
            formData.append('userId', userId);
            formData.append('punishmentType', action);
            formData.append('durationDays', 7); // 固定设为7天
            
            const reason = reportId ? 
                `处理举报 #${reportId}` : 
                `管理员处罚：${action === 'mute' ? '禁言' : '封禁'}`;
            
            formData.append('reason', reason);
            
            // 如果有关联的举报ID
            if (reportId) {
                formData.append('reportId', reportId);
                formData.append('relatedReportId', reportId);
            }
            
            // 发送请求到API
            fetch('/api/admin/punishments', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                console.log('处罚API响应状态:', response.status);
                if (!response.ok) {
                    return response.text().then(text => {
                        console.error('处罚API错误响应:', text);
                        try {
                            const errorData = JSON.parse(text);
                            throw new Error(errorData.message || errorData.detail || '处罚提交失败');
                        } catch (e) {
                            throw new Error(`处罚提交失败: ${response.status} ${response.statusText}`);
                        }
                    });
                }
                return response.json();
            })
            .then(data => {
                console.log('处罚提交成功:', data);
                
                // 如果有关联的举报ID，更新举报状态
                if (reportId) {
                    return updateReportStatus(reportId, 'resolved')
                        .then(() => data);
                }
                return data;
            })
            .then(data => {
                // 显示成功消息
                showResult(data.message || `成功${action === 'mute' ? '禁言' : '封禁'}用户`, true);
                
                // 刷新用户列表
                document.getElementById('refreshUsersBtn').click();
                
                // 如果有关联的举报ID，也刷新举报列表
                if (reportId) {
                    document.getElementById('refreshReportsBtn').click();
                }
                
                // 更新仪表盘统计数据
                fetchStatistics();
            })
            .catch(error => {
                console.error('提交处罚失败:', error);
                showResult(error.message || '处罚提交失败，请重试', false);
            });
        }

        // 设置活动过滤器
        function setActiveFilter(button) {
            // 移除所有活动类
            document.querySelectorAll('.btn-group .btn').forEach(el => {
                el.classList.remove('active');
            });
            
            // 添加活动类到当前按钮
            button.classList.add('active');
        }
        
        // 获取当前选中的举报状态
        function getCurrentReportStatus() {
            const activeFilter = document.querySelector('.btn-group .active');
            let status = 'all';
            if (activeFilter) {
                if (activeFilter.id === 'filterPendingReports') status = 'pending';
                else if (activeFilter.id === 'filterResolvedReports') status = 'resolved';
                else if (activeFilter.id === 'filterRejectedReports') status = 'rejected';
            }
            return status;
        }

    </script>
</body>
</html>